<template>
   <div class="app-container">
      <!-- 条件搜索 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="盘点编号" prop="inventoryId">
            <el-input v-model="pagin.search.inventoryId" placeholder="请输入盘点编号" clearable @keyup.enter="handleQuery"
               style="width: 200px;" />
         </el-form-item>
         <el-form-item label="盘点仓库" prop="warehouseId">
            <el-input v-model="pagin.search.warehouse" placeholder="请输入仓库" clearable @keyup.enter="handleQuery"
               style="width: 200px;" />
         </el-form-item>
         <el-form-item label="盘点结果" prop="countResult">
            <el-select v-model="pagin.search.countResult" placeholder="请选择" clearable style="width: 200px;">
               <el-option v-for="dict in resultList" :key="dict.value" :label="dict.value" :value="dict.value" />
            </el-select>
         </el-form-item>
         <el-form-item label="状态" prop="approvalStatus">
            <el-select v-model="pagin.search.approvalStatus" placeholder="请选择" clearable style="width: 200px;">
               <el-option v-for="dict in tatusList" :key="dict.typeId" :label="dict.typeName" :value="dict.typeId" />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDeleteList">删除</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 表格展示 -->
      <el-table v-loading="loading" :data="checkList" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column prop="inventoryId" label="盘点编号"></el-table-column>
         <el-table-column prop="warehouse" label="盘点仓库"></el-table-column>
         <el-table-column prop="inventoryTaker" label="盘点人"></el-table-column>
         <el-table-column prop="countResult" label="盘点结果"></el-table-column>
         <el-table-column prop="inventoryDate" label="盘点日期"></el-table-column>
         <el-table-column prop="inventoryNotes" label="盘点备注"></el-table-column>
         <el-table-column prop="approver" label="审批人"></el-table-column>
         <el-table-column prop="approvalDate" label="审批日期"></el-table-column>
         <el-table-column label="状态" prop="approvalStatus" :formatter="row => getStatusNameById(row.approvalStatus)">
         </el-table-column>




         <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-tooltip content="查询" placement="top">
                  <el-button type="text" icon="Search" @click="handleSelectDetail(scope.row.inventoryId)"></el-button>
               </el-tooltip>
               <el-tooltip content="修改" placement="top">
                  <el-button type="text" icon="Edit" @click="checkUpdate(scope.row)"></el-button>
               </el-tooltip>
               <el-tooltip content="删除" placement="top">
                  <el-button type="text" icon="Delete" @click="handleDelete(scope.row)"></el-button>
               </el-tooltip>
            </template>
         </el-table-column>
      </el-table>

      <!--分页组件-->
      <div class="pagination-container">
         <el-pagination class="pagiantion" @current-change="handleCurrentChange" :current-page="pagin.page"
            :page-size="pagin.count" layout="total, prev, pager, next, jumper" :total="pagin.total">
         </el-pagination>
      </div>


      <!-- 添加或修改盘点对话框 -->
      <el-dialog v-if="open" :title="title" v-model="open" append-to-body>
         <el-form ref="checkRef" :model="form" :rules="rules" label-width="100px">



            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="盘点编号" prop="inventoryId">
                     <el-input v-model="form.inventoryId" maxlength="20" readonly :style="{ width: '100%' }" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="盘点仓库" prop="warehouseId">
                     <el-select v-model="form.warehouseId" placeholder="请选择" clearable :style="{ width: '100%' }">
                        <el-option v-for="dict in WareHouseOptions" :key="dict.warehouseId" :label="dict.warehouseName"
                           :value="dict.warehouseId" />
                     </el-select>
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="盘点结果" prop="countResult">
                     <el-select v-model="form.countResult" placeholder="请选择" clearable :style="{ width: '100%' }">
                        <el-option v-for="dict in resultList" :key="dict.value" :label="dict.value"
                           :value="dict.value" />
                     </el-select>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="审批人" prop="approverId">
                     <el-select v-model="form.approverId" placeholder="请选择" clearable :style="{ width: '100%' }">
                        <el-option v-for="dict in ApproverOptions" :key="dict.userId" :label="dict.nickName"
                           :value="dict.userId" />
                     </el-select>
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="状态" prop="approvalStatus">
                     <el-select v-model="form.approvalStatus" placeholder="请选择" clearable :style="{ width: '100%' }">
                        <el-option v-for="dict in tatusList" :key="dict.typeId" :label="dict.typeName"
                           :value="dict.typeId" />
                     </el-select>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="盘点日期" prop="inventoryDate">
                     <el-date-picker v-model="form.inventoryDate" type="date" placeholder="选择盘点日期"
                        :picker-options="{ firstDayOfWeek: 1 }" :style="{ width: '100%' }" />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="盘点人" prop="inventoryTaker">
                     <el-input v-model="form.inventoryTaker" placeholder="请输入盘点人" maxlength="20"
                        :style="{ width: '100%' }" />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row>

               <!-- 添加盘点明细按钮 -->
               <el-col :span="12" style="text-align: left;">
                  <el-button type="primary" plain icon="Plus" @click="handleAddDetail">新增盘点明细</el-button>
               </el-col>

               <!-- 表格展示 -->
               <el-table v-loading="loading" :data="AddetailList" @selection-change="handleSelectionChange">
                  <el-table-column prop="inventoryDetailId" label="明细编号"></el-table-column>
                  <el-table-column prop="inventoryCountId" label="盘点编号"></el-table-column>
                  <el-table-column prop="variantProductId" label="产品编号"></el-table-column>
                  <el-table-column prop="productName" label="产品名称"></el-table-column>
                  <el-table-column prop="bookQuantity" label="账面数量"></el-table-column>
                  <el-table-column prop="actualQuantity" label="实际数量"></el-table-column>
                  <el-table-column prop="quantityDifference" label="差异数量"></el-table-column>
                  <el-table-column prop="differenceReason" label="差异原因"></el-table-column>
                  <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
                     <template #default="scope">
                        <el-tooltip content="修改" placement="top">
                           <el-button type="text" icon="Edit" @click="DetailUpdate(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                           <el-button type="text" icon="Delete"
                              @click="handleDeleteSeleteDetail(scope.row)"></el-button>
                        </el-tooltip>
                     </template>
                  </el-table-column>
               </el-table>
               <!--分页组件-->
               <div class="pagination-container">
                  <el-pagination class="pagiantion" @current-change="handleDetail" :current-page="detailPage.page"
                     :page-size="detailPage.count" layout="total, prev, pager, next, jumper" :total="detailPage.total">
                  </el-pagination>
               </div>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="checkFrom">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>


      <!-- 添加或修改盘点明细对话框 -->
      <el-dialog v-if="openTwo" :title="titleTwo" v-model="openTwo" append-to-body>
         <el-form ref="detailRef" :model="detail.search" :rules="rules" label-width="100px">
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="盘点编号" prop="inventoryCountId">
                     <el-input v-model="detail.search.inventoryCountId" maxlength="20" readonly />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="产品编号" prop="variantProductId">
                     <el-input v-model="detail.search.variantProductId" placeholder="请输入产品编号" />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="产品名称" prop="productName">
                     <el-input v-model="detail.search.productName" placeholder="请输入产品名称" maxlength="20" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="账面数量" prop="bookQuantity">
                     <el-input v-model="detail.search.bookQuantity" placeholder="请输入账面数量" />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="实际数量" prop="actualQuantity">
                     <el-input v-model="detail.search.actualQuantity" placeholder="请输入实际数量" maxlength="20" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="差异数量" prop="quantityDifference">
                     <el-input v-model="detail.search.quantityDifference" placeholder="请输入差异数量" />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="差异原因" prop="differenceReason">
                     <el-input v-model="detail.search.differenceReason" type="textarea" placeholder="请输入差异原因"
                        maxlength="200" :rows="3" />
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="detailFrom">确 定</el-button>
               <el-button @click="cancelTwo">取 消</el-button>
            </div>
         </template>
      </el-dialog>


      <!-- 查询盘点明细对话框 -->
      <el-dialog v-if="openThird" :title="titleThird" v-model="openThird" append-to-body>
         <!-- 表格展示 -->
         <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
            <el-table-column prop="inventoryDetailId" label="明细编号"></el-table-column>
            <!-- <el-table-column prop="inventoryCountId" label="盘点编号"></el-table-column> -->
            <el-table-column prop="variantProductId" label="产品编号"></el-table-column>
            <el-table-column prop="productName" label="产品名称"></el-table-column>
            <el-table-column prop="bookQuantity" label="账面数量"></el-table-column>
            <el-table-column prop="actualQuantity" label="实际数量"></el-table-column>
            <el-table-column prop="quantityDifference" label="差异数量"></el-table-column>
            <el-table-column prop="differenceReason" label="差异原因"></el-table-column>
            <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
               <template #default="scope">
                  <el-tooltip content="修改" placement="top">
                     <el-button type="text" icon="Edit" @click="DetailUpdate(scope.row)"></el-button>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                     <el-button type="text" icon="Delete" @click="handleDeleteDetail(scope.row)"></el-button>
                  </el-tooltip>
               </template>
            </el-table-column>
         </el-table>
         <!--分页组件-->
         <div class="pagination-container">
            <el-pagination class="pagiantion" @current-change="handleChange" :current-page="queryParams.page"
               :page-size="queryParams.count" layout="total, prev, pager, next, jumper" :total="queryParams.total">
            </el-pagination>
         </div>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="cancelThird">取 消</el-button>
            </div>
         </template>
      </el-dialog>


   </div>
</template>

<script setup name="Dept">
import { findTatus } from "@/api/reserve/insto";
import { listCheck, delCheck, getDetail, delDetail, getWareHouse, getApprover, getMaxID, addDetail, addCheck, getCheck, getDetailById, molDetail, molCheck, delDetailByInventory } from "@/api/reserve/check";
import { getCurrentInstance, nextTick, reactive, ref } from "vue";
import { ElMessage } from 'element-plus';
const { proxy } = getCurrentInstance();
const tatusList = ref([]);
const checkList = ref([]);
const detailList = ref([]);
const AddetailList = ref([]);
const open = ref(false);
const openTwo = ref(false);
const openThird = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const titleTwo = ref("");
const titleThird = ref("");
const MaxID = ref(0);
const WareHouseOptions = ref([]);
const ApproverOptions = ref([]);
const data = reactive({
   form: {

   },
   detail: {
      search: {}
   },
   queryParams: {
      page: 1,
      total: 10,
      count: 5,
      search: {
         inventoryCountId: undefined,
      },
   },

   resultList: [{ value: '正常' }, { value: '异常' }],
   pagin: {
      page: 1,
      total: 10,
      count: 5,
      search: {
         inventoryId: undefined,
         warehouse: undefined,
         approvalStatus: undefined,
         countResult: undefined,

      },
   },
   detailPage: {
      page: 1,
      total: 0,
      count: 5,
      search: {
         inventoryCountId: undefined,
      },
   },
   rules: {
      warehouseId: [
         { required: true, message: "仓库不能为空", trigger: "blur" },
      ],
      countResult: [
         { required: true, message: "盘点结果不能为空", trigger: "change" },
      ],
      inventoryTaker: [
         { required: true, message: "盘点人不能为空", trigger: "blur" },
      ],
      approverId: [
         { required: true, message: "审批人不能为空", trigger: "blur" },
      ],
      approvalStatus: [
         { required: true, message: "审批状态不能为空", trigger: "change" },
      ],
      inventoryDate: [
         { required: true, message: "盘点日期不能为空", trigger: "blur" },
      ],
      variantProductId: [
         { required: true, message: "变体产品编号不能为空", trigger: "blur" },
      ],
      productName: [
         { required: true, message: "产品名称不能为空", trigger: "blur" },
      ],
      bookQuantity: [
         { required: true, message: "账面数量不能为空", trigger: "blur" },
      ],
      actualQuantity: [
         { required: true, message: "实际数量不能为空", trigger: "blur" },
      ],
      quantityDifference: [
         { required: true, message: "差异数量不能为空", trigger: "blur" },
      ],

   },
});

const { queryParams, resultList, form, rules, detail, pagin, detailPage } = toRefs(data);

/** 查询部门列表 */
function getList() {
   loading.value = true;
   listCheck(pagin.value).then(response => {
      checkList.value = response.data.list;
      pagin.value.page = response.data.pageNum;
      pagin.value.total = response.data.total;
      loading.value = false;
   });
}
//审批状态
function tatus() {
   findTatus().then(response => {
      tatusList.value = response.data;
      getList();
   })
}
//切换页码
function handleCurrentChange(currentPage) {
   pagin.value.page = currentPage; // 更新当前页码
   //执行查询
   getList();
}
//切换页码
function handleChange(currentPage) {
   queryParams.value.page = currentPage; // 更新当前页码
   //执行查询
   handleSelectDetail(queryParams.value.search.inventoryCountId);
}
//切换页码
function handleDetail(currentPage) {
   detailPage.value.page = currentPage; // 更新当前页码
   //执行查询
   selectAddDetail()
}

/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
   delDetailByInventory(MaxID.value);
}
// 取消查询明细窗
function cancelThird() {
   openThird.value = false;
   queryParams.value.page = 1;
}
// 取消新增明细窗
function cancelTwo() {
   openTwo.value = false;
}
/** 表单重置 */
function reset() {
   form.value = {
      inventoryId: MaxID.value,
      approvalStatus: '等待审批',
      countResult: '正常'
   };
   proxy.resetForm("checkRef");
}
// 最大盘点单ID
function maxId() {
   getMaxID().then(response => {
      MaxID.value = response.data;
      reset()
   })
}

/** 搜索按钮操作 */
function handleQuery() {
   getList();
}

/** 重置按钮操作 */
function resetQuery() {
   pagin.value.search = {};
   handleQuery();
}
/** 新增盘点单按钮操作 */
function handleAdd(row) {
   maxId();
   WareHouseList();
   ApproverList();
   open.value = true;
   title.value = "添加盘点单";
   AddetailList.value = [];
}
// 仓库下拉列表
function WareHouseList() {
   getWareHouse().then(response => {
      WareHouseOptions.value = response.data;

   }).catch(error => {
      console.error('Failed to fetch warehouse data:', error);
   });
}
// 审批人下拉列表
function ApproverList() {
   getApprover().then(response => {
      ApproverOptions.value = response.data;
   }).catch(error => {
      console.error('Failed to fetch warehouse data:', error);
   });
}
/** 查询盘点明细按钮操作 */
function handleSelectDetail(inventoryId) {
   queryParams.value.search.inventoryCountId = inventoryId;
   loading.value = true;
   if (queryParams.value.page == null) {
      queryParams.value.page = 1;
   }
   getDetail(queryParams.value).then(response => {
      detailList.value = response.data.records;
      queryParams.value.page = response.data.page;
      queryParams.value.total = response.data.total;
   })
   openThird.value = true;
   titleThird.value = "查询盘点明细";
   loading.value = false;
}
/** 新增盘点明细按钮操作 */
async function handleAddDetail() {
   if (form.value.warehouseId == null) {
      ElMessage.error("仓库未选择");
   } else {
      detail.value = {
         search: {
            inventoryCountId: form.value.inventoryId
         }
      }
      openTwo.value = true;
      titleTwo.value = "添加盘点明细单";
   }
}

/** 盘点修改按钮操作 */
async function checkUpdate(row) {
   await WareHouseList();
   await ApproverList();
   getCheck(row.inventoryId).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改盘点";
      detail.value.search.inventoryCountId = row.inventoryId;
      selectAddDetail();
   });
}
/** 盘点明细修改按钮操作 */
function DetailUpdate(row) {
   detail.value = {};
   getDetailById(row.inventoryDetailId).then(response => {
      detail.value.search = response.data;
      openTwo.value = true;
      titleTwo.value = "修改盘点明细";
   });
}

/** 盘点明细提交按钮 */
function detailFrom() {
   proxy.$refs["detailRef"].validate(valid => {
      if (valid) {
         if (detail.value.search.inventoryDetailId !== undefined) {
            molDetail(detail.value).then(response => {
               proxy.$modal.msgSuccess("修改成功");
               openTwo.value = false;
               selectAddDetail();
            });

         } else {
            addDetail(detail.value).then(response => {
               proxy.$modal.msgSuccess("新增成功");
               openTwo.value = false;
               selectAddDetail();
            });

         }
      }
   });
}



// 添加盘点明细后查询
function selectAddDetail() {
   detailPage.value.search.inventoryCountId = detail.value.search.inventoryCountId;
   if (detailPage.value.page == null) {
      detailPage.value.page = 1;
   }
   getDetail(detailPage.value).then(response => {
      AddetailList.value = response.data.records;
      detailPage.value.page = response.data.page;
      detailPage.value.total = response.data.total;
   })
}

/** 盘点单提交按钮 */
function checkFrom() {
   proxy.$refs["checkRef"].validate(valid => {
      form.value = {
         search: form.value
      }
      if (valid) {
         if (form.value.search.inventoryId != MaxID.value) {
            molCheck(form.value).then(response => {
               proxy.$modal.msgSuccess("修改成功");
               form.value = {};
               open.value = false;
               getList();
            });

         } else {
            console.log(form.value);
            addCheck(form.value).then(response => {
               proxy.$modal.msgSuccess("新增成功");
               form.value = {};
               open.value = false;
               getList();
            });

         }
      }
   });
}


/** 删除盘点单按钮操作 */
function handleDelete(row) {
   proxy.$modal.confirm('是否确认删除名称为"' + row.inventoryId + '"的数据项?').then(function () {
      return delCheck(row.inventoryId);
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}
/** 删除查询的盘点单明细按钮操作 */
function handleDeleteDetail(row) {
   proxy.$modal.confirm('是否确认删除名称为"' + row.inventoryDetailId + '"的数据项?').then(function () {
      return delDetail(row.inventoryDetailId);
   }).then(() => {
      handleSelectDetail(row.inventoryCountId);
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}
/** 删除盘点单明细按钮操作 */
function handleDeleteSeleteDetail(row) {
   proxy.$modal.confirm('是否确认删除名称为"' + row.inventoryDetailId + '"的数据项?').then(function () {
      return delDetail(row.inventoryDetailId);
   }).then(() => {
      detail.value.search.inventoryCountId = row.inventoryCountId;
      selectAddDetail();
      proxy.$modal.msgSuccess("删除成功");

   }).catch(() => { });
}
// 批量删除
// function handleDeleteList(selection){
//    selection.map(item => item.configId)
// }

function getStatusNameById(cellValue) {
   for (const status of tatusList.value) {
      if (status.typeId == cellValue) {
         console.log(status.typeName)
         return status.typeName;
      }
   }
   // 如果没有找到匹配的项，可以返回一个默认值或者null
   return null; // 或者 'Unknown', 或者其他你认为合适的值
}

tatus();
WareHouseList();
ApproverList();
</script>
